package com.world.rickcloudendpoint.common.utils;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * @description: 端序转换
 * @author: jlsong
 * @date: 2021/12/21 23:23:58
 * @version: 1.0
 */
public class ByteBufferEndianUtils implements ByteBufferEndian {

    private static ByteBuffer shortBuffer = ByteBuffer.allocate(2);
    private static ByteBuffer intBuffer = ByteBuffer.allocate(4);
    private static ByteBuffer longBuffer = ByteBuffer.allocate(8);

    @Override
    public short bytes2Short(byte[] bytes) {
        shortBuffer.clear();
        shortBuffer.put(bytes, 0, bytes.length);
        shortBuffer.flip();
        return shortBuffer.getShort();
    }

    @Override
    public short bytes2ShortBigEndian(byte[] bytes) {
        shortBuffer.clear();
        shortBuffer.order(ByteOrder.LITTLE_ENDIAN);
        shortBuffer.put(bytes, 0, bytes.length);
        shortBuffer.flip();
        return shortBuffer.getShort();
    }

    @Override
    public short bytes2ShortBigEndian(byte[] bytes, int pos) {
        shortBuffer.clear();
        shortBuffer.order(ByteOrder.LITTLE_ENDIAN);
        shortBuffer.put(bytes, pos, 2);
        shortBuffer.flip();
        return shortBuffer.getShort();
    }

    @Override
    public int bytes2Int(byte[] bytes) {
        intBuffer.clear();
        intBuffer.put(bytes, 0, bytes.length);
        intBuffer.flip();
        return intBuffer.getInt();
    }

    @Override
    public int bytes2IntBigEndian(byte[] bytes) {
        intBuffer.clear();
        intBuffer.order(ByteOrder.LITTLE_ENDIAN);
        intBuffer.put(bytes, 0, bytes.length);
        intBuffer.flip();
        return intBuffer.getInt();
    }

    @Override
    public int bytes2IntBigEndian(byte[] bytes, int pos) {
        intBuffer.clear();
        intBuffer.order(ByteOrder.LITTLE_ENDIAN);
        intBuffer.put(bytes, pos, 4);
        intBuffer.flip();
        return intBuffer.getInt();
    }

    @Override
    public long bytes2Long(byte[] bytes) {
        longBuffer.clear();
        longBuffer.put(bytes, 0, bytes.length);
        longBuffer.flip();
        return longBuffer.getLong();
    }

    @Override
    public long bytes2LongBigEndian(byte[] bytes) {
        longBuffer.clear();
        longBuffer.order(ByteOrder.LITTLE_ENDIAN);
        longBuffer.put(bytes, 0, bytes.length);
        longBuffer.flip();
        return longBuffer.getLong();
    }

    @Override
    public long bytes2LongBigEndian(byte[] bytes, int pos) {
        longBuffer.clear();
        longBuffer.order(ByteOrder.LITTLE_ENDIAN);
        longBuffer.put(bytes, pos, 8);
        longBuffer.flip();
        return longBuffer.getLong();
    }
}
